package org.mikhaylov.cp.service.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.mikhaylov.cp.service.command.ServiceCommand;
import org.mikhaylov.cp.service.db.entities.User;
import org.mikhaylov.cp.service.hibernate.HibernateManager;
import org.mikhaylov.cp.service.response.ResponseType;

public class RefillServiceCommand extends ServiceCommand {

	private static final long serialVersionUID = 5182169035195173314L;

	private User user = null;
	private Double value = null;

	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getAttribute("user") == null
				|| !(request.getAttribute("user") instanceof User)
				|| request.getAttribute("value") == null
				|| !(request.getAttribute("value") instanceof Double)) {
			response.setType(ResponseType.ERROR);
			response.setMeta("Bad params");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		user = (User) request.getAttribute("user");
		value = (Double) request.getAttribute("value");
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {
		HibernateManager.getInstance().updateUserBalance(user, value);
		response.setType(ResponseType.SUCCESS);
		response.setMeta("Balance has been refilled successfully");
	}

}
